package com.cyh.structurealgorithm;

import android.util.Log;

public class SparseArr {
    static int arr[][] = new int[11][11];
    static int spareArr[][];
    public static void arrToSpare() {
        arr[2][5] = 5;
        arr[6][9] = 8;
        int num = 0;
        Log.i("tag", "原始数组：");
        for(int i = 0; i < arr.length; i++) {
            String str = "";
            for(int j = 0; j < arr[i].length; j++) {
                str = str + " " + arr[i][j];
                if(arr[i][j] != 0) {
                    num++;
                }
            }
            Log.i("tag", str);
        }
        spareArr= new int[num+1][3];
        spareArr[0][0] = arr.length;
        spareArr[0][1] = arr[0].length;
        spareArr[0][2] = num;

        num = 0;
        for(int i = 0; i < arr.length; i++) {
            for(int j = 0; j < arr[i].length; j++) {
                if(arr[i][j] != 0) {
                    num++;
                    spareArr[num][0] = i;
                    spareArr[num][1] = j;
                    spareArr[num][2] = arr[i][j] ;
                }
            }
        }

        Log.i("tag", "稀疏数组：");
        for(int i = 0; i < spareArr.length; i++) {
            String str = "";
            for(int j = 0; j < spareArr[i].length; j++) {
                str = str + " " + spareArr[i][j];
            }
            Log.i("tag", str);
        }
    }

    public static void spareToArr() {
        arr = new int[spareArr[0][0]][spareArr[0][1]];
        for(int i = 1; i < spareArr.length; i++) {
            arr[spareArr[i][0]][spareArr[i][1]] = spareArr[i][2];
        }

        Log.i("tag", "稀疏数组转原始数组：");
        for(int i = 0; i < arr.length; i++) {
            String str = "";
            for(int j = 0; j < arr[i].length; j++) {
                str = str + " " + arr[i][j];
            }
            Log.i("tag", str);
        }

    }
}
